package com.sw.paisong.security;

import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.sw.paisong.config.AppConfig;
import com.sw.paisong.entity.ManagerEntity;
import com.sw.paisong.service.ManagerService;
import com.sw.paisong.util.SessionUtil;
import com.sw.paisong.vo.SessionVO;

public class ShiroRealm extends AuthorizingRealm {

	private static final Logger logger = LoggerFactory.getLogger(ShiroRealm.class);

	@Autowired
	ManagerService managerService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		// TODO Auto-generated method stub
		logger.debug("doGetAuthorizationInfo");
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		// TODO Auto-generated method stub
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String Username = token.getUsername();

		AppConfig appConfig = AppConfig.getInstance();
		if (appConfig != null) {
			if (Username.equals(appConfig.getSuperAccount())) {
				SessionVO sessionVO = new SessionVO(appConfig);
				SessionUtil.setCurrentSession(sessionVO);
				return new SimpleAuthenticationInfo(Username, DigestUtils.md5Hex(appConfig.getSuperPasswd()), getName());
			}
		}

		List<ManagerEntity> managerList = managerService.getByAccount(token.getUsername());
		if (managerList.size() > 0) {
			ManagerEntity manager = managerList.get(0);
			SessionUtil.setCurrentSession(new SessionVO(manager));
			return new SimpleAuthenticationInfo(manager.getAccount(), manager.getPasswd(), getName());
		}
		return null;

		// List<MemberModel> memberList =
		// memberService.getByUsername(token.getUsername());
		// if (memberList.size() > 0) {
		// MemberModel member = memberList.get(0);
		// UserUtils.setCurrentUser(new SessionVO(member));
		// if (member.getType().equals(UserType.ORG.getValue())) {
		// return new SimpleAuthenticationInfo(member.getUsername(),
		// member.getPassword(), getName());
		// } else {
		// return null;
		// }
		// } else {
		// return null;
		// }
	}
	
	
}
